package com.xiaoshuidi.cloud.module.report.service.finance;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.report.controller.finance.vo.*;
import com.xiaoshuidi.cloud.module.report.convert.finance.OwnerIncomeDetailConvert;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.OwnerIncomeDetailReportDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.OwnerIncomeSummaryReportDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.OwnerIncomeDetailReportMapper;
import com.xiaoshuidi.cloud.module.report.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.report.framework.security.config.ConfigValues;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;


@Service
@RequiredArgsConstructor
@Slf4j
public class OwnerIncomeDetailReportServiceImpl implements OwnerIncomeDetailReportService {

    private final OwnerIncomeDetailReportMapper ownerIncomeDetailReportMapper;
    private final OosFileService oosFileService;
    private final ConfigValues configValues;

    @Override
    public PageResult<OwnerDetailIncomePageRespVO> detailIncomePage(OwnerDetailIncomePageReqVO reqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        reqVO.setTenantId(loginUser.getTenantId());
        long num = ownerIncomeDetailReportMapper.countListForPage(reqVO);
        List<OwnerIncomeDetailReportDO> detailReports = ownerIncomeDetailReportMapper.selectListForPage(reqVO);
        List<OwnerDetailIncomePageRespVO> pageResp = OwnerIncomeDetailConvert.INSTANCE.convertDetailIncomePage(detailReports);
        return new PageResult<>(pageResp,num);
    }


    @Override
    public ExportRespVO detailIncomeExport(OwnerDetailIncomePageReqVO req) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        req.setTenantId(loginUser.getTenantId());
        //暂时不分页，当月合同数不会超过2000
        String fileName =  req.getStatisticsMonth() + "成本汇总明细表.xlsx";
        String filePath = configValues.getNfsPath() + File.separator +fileName;
        ExcelWriter excelWriter = EasyExcel.write(filePath, OwnerDetailIncomeExportRespVO.class).build();
        WriteSheet sheet = EasyExcel.writerSheet("sheet1").build();
        List<OwnerIncomeDetailReportDO> reportDOList = ownerIncomeDetailReportMapper.selectListForExport(req);
        if(CollectionUtils.isEmpty(reportDOList)){
            throw new ServiceException(ErrorCodeConstants.OWNER_DETAIL_INCOME_NOT_EXISTS);
        }
        List<OwnerDetailIncomeExportRespVO> list =OwnerIncomeDetailConvert.INSTANCE.convertDetailForExport(reportDOList);
        excelWriter.write(list, sheet);
        excelWriter.finish();
        //上传到oos返回URL
        String url = oosFileService.oosUploadFile(new File(filePath));
        ExportRespVO resp = new ExportRespVO();
        if(url.startsWith("http:")){
            url = url.replace("http:","https:");
        }
        resp.setUrl(url);
        resp.setFileName(fileName);
        return resp;
    }

    @Override
    public OwnerIncomeDetailReportDO getRecentIncomeReport(Long contractId,String currentMonth) {
        LambdaQueryWrapper<OwnerIncomeDetailReportDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OwnerIncomeDetailReportDO::getContractId, contractId);
        queryWrapper.lt(OwnerIncomeDetailReportDO::getStatisticsMonth,currentMonth);
        queryWrapper.orderByDesc(OwnerIncomeDetailReportDO::getId);
        queryWrapper.last("limit 1");
        List<OwnerIncomeDetailReportDO> incomeDetailReportDOS = ownerIncomeDetailReportMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(incomeDetailReportDOS)) {
            return null;
        }
        return incomeDetailReportDOS.get(0);
    }

    @Override
    public long countDetailsInCurrentMonth(String currentMonth) {
        return ownerIncomeDetailReportMapper.countDetailsInCurrentMonth(currentMonth);
    }

    @Override
    public List<OwnerIncomeDetailReportDO> selectDetailsInCurrentMonth(String currentMonth) {
        LambdaQueryWrapper<OwnerIncomeDetailReportDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OwnerIncomeDetailReportDO::getStatisticsMonth, currentMonth);
        return ownerIncomeDetailReportMapper.selectList(queryWrapper);
    }

    @Override
    public List<OwnerIncomeDetailReportDO> selectDetailsInCurrentMonthInTurn(String currentMonth,Integer from,Integer pageSize) {
        LambdaQueryWrapper<OwnerIncomeDetailReportDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OwnerIncomeDetailReportDO::getStatisticsMonth, currentMonth);
        queryWrapper.orderByAsc(OwnerIncomeDetailReportDO::getId);
        queryWrapper.last("limit "+from+","+pageSize);
        return ownerIncomeDetailReportMapper.selectList(queryWrapper);
    }

    @Override
    public OwnerIncomeDetailReportDO selectDetailsByContractIdInCurrentMonth(Long contractId, String currentMonth) {
        return ownerIncomeDetailReportMapper.selectDetailsByContractIdInCurrentMonth(contractId,currentMonth);
    }

    @Override
    public BigDecimal sumTotalRentAndWaterByContractId(Long contractId) {
        return ownerIncomeDetailReportMapper.sumTotalRentAndWaterByContractId(contractId);
    }

    @Override
    public void insertBatch(List<OwnerIncomeDetailReportDO> list){
        ownerIncomeDetailReportMapper.insertBatch(list);
    }
    @Override
    public void updateBatch(List<OwnerIncomeDetailReportDO> list){
        ownerIncomeDetailReportMapper.updateBatch(list,list.size());
    }

    @Override
    public List<OwnerIncomeDetailReportDO> selectDetailsInCurrentMonthAndContractIds(String currentMonth, List<Long> contractIds) {
        LambdaQueryWrapper<OwnerIncomeDetailReportDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OwnerIncomeDetailReportDO::getStatisticsMonth, currentMonth);
        queryWrapper.in(OwnerIncomeDetailReportDO::getContractId,contractIds);
        return ownerIncomeDetailReportMapper.selectList(queryWrapper);
    }

    @Override
    public List<OwnerIncomeSummaryReportDO> selectDetailsInCurrentMonthGroupByApartmentId(String currentMonth){
       return ownerIncomeDetailReportMapper.selectDetailsInCurrentMonthGroupByArea(currentMonth);
    }


}
